package com.blog.blog.interceptor;

import com.blog.blog.dao.pojo.LoginTicket;
import com.blog.blog.dao.pojo.SysUser;
import com.blog.blog.service.SysUserService;
import com.blog.blog.utils.CookieUtil;
import com.blog.blog.utils.UserThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

@Component
public class LoginTokenInterceptor implements HandlerInterceptor {

    @Autowired
    private SysUserService sysUserService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //String ticket = CookieUtil.getValue(request, "ticket")
        String ticket= request.getHeader("Authorization");
        if (ticket != null) {
            LoginTicket loginTicket = sysUserService.findLoginTicket(ticket);
            if (loginTicket != null) {
                SysUser user = sysUserService.findUserById(loginTicket.getUserId());
                UserThreadLocal.put(user);
                Authentication authentication = new UsernamePasswordAuthenticationToken(
                        user, user.getPassword(), sysUserService.getAuthorities(user.getId()));
                SecurityContextHolder.setContext(new SecurityContextImpl(authentication));
            }
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
        //SecurityContextHolder.clearContext();
    }

}
